<?php
/*--------------------------------------------------------------------
 小微OA系统 - 让工作更轻松快乐

 Copyright (c) 2013 http://www.smeoa.com All rights reserved.

 Author:  jinzhu.yin<smeoa@qq.com>

 Support: https://git.oschina.net/smeoa/xiaowei
 --------------------------------------------------------------*/
use sef\controller;
use sef\model;

class user_controller extends base_controller {

    function _search_filter(&$map) {
        $keyword = get('keyword');
        if (!empty($keyword)) {
            $map[] = array('name', 'like', $keyword);
            $map[] = array('emp_no', 'like', $keyword);
        }
    }

    public function index() {
        $where_position[] = array('is_del', 'eq', 0);
        $position_list = model('position') -> where($where_position) -> order('sort asc') -> get_field('id,name', true);
        $this -> assign('position_list', $position_list);

        $where_dept[] = array('is_del', 'eq', 0);
        $dept_list = model('dept') -> where($where_dept) -> order('sort asc') -> get_field('id,name');
        $this -> assign('dept_list', $dept_list);

        if (post('eq_is_del')) {
            $eq_is_del = post('eq_is_del');
        } else {
            $eq_is_del = "0";
        }

        $this -> assign('eq_is_del', $eq_is_del);

        $map = $this -> _search();
        if (method_exists($this, '_search_filter')) {
            $this -> _search_filter($map);
        }
        $map[] = array('is_del', 'eq', $eq_is_del);

        $model = model('user');
        if (!empty($model)) {
            $this -> _list($model, $map, "emp_no");
        }
        $this -> display();
    }

    public function add() {

        $where[] = array('is_del', 'eq', 0);
        $position_list = model('position') -> where($where) -> order('sort asc') -> get_field('id,name');
        $this -> assign('position_list', $position_list);

        $dept_list = model('dept') -> where($where) -> order('sort asc') -> get_field('id,name');
        $this -> assign('dept_list', $dept_list);

        $this -> display();
    }

    public function read($id) {
        $field = 'id,emp_no,name,sex,birthday,dept_id,position_id,office_tel,mobile_tel,email,duty,is_del,pic';
        $vo = model('user') -> select($field) -> find($id);
        if (IS_AJAX) {
            if ($vo !== false) {// 读取成功
                $return['data'] = $vo;
                $return['status'] = 1;
                $return['info'] = "读取成功";
                ajax_return($return);
            } else {
                $return['status'] = 0;
                $return['info'] = "读取错误";
                ajax_return($return);
            }
        }
        $this -> assign('vo', $vo);
        $this -> display();
    }

    // 插入数据
    protected function _insert($name = "user") {
        // 创建数据对象
        $model = model('user');
        if (!$model -> create()) {
            $this -> error($model -> getError());
        } else {
            // 写入帐号数据
            $model -> letter = get_letter($model -> name);
            $model -> password = md5($model -> emp_no);
            $model -> dept_id = request('dept_id');
            $model -> openid = $model -> emp_no;
            $model -> westatus = 1;
            $emp_no = $model -> emp_no;
            $name = $model -> name;
            $mobile_tel = $model -> mobile_tel;

            if ($result = $model -> add()) {
                $data['id'] = $result;
                model('user_config') -> add($data);
                if (get_system_config('system_license')) {
                    if (!empty($mobile_tel)) {
                        import('weixin/work/txl_api.php');

                        $txl = new \TXL_API();

                        $user_info = D('UserView') -> find($user_id);
                        $wechat_data["userid"] = $user_info['emp_no'];
                        $wechat_data["name"] = $user_info['name'];
                        $wechat_data["mobile"] = trim($user_info['mobile_tel'], '+-');
                        $wechat_data["department"] = array($user_info['dept_id']);
                        $wechat_data["position"] = $user_info['position_name'];
                        $wechat_data["email"] = $user_info['email'];

                        if ($user_info['is_del'] == 1) {
                            $wechat_data["enable"] = 0;
                        } else {
                            $wechat_data["enable"] = 1;
                        }
                        $txl -> createUser($wechat_data);
                    }
                }
                $this -> assign('jump_url', get_return_url());
                $this -> success('用户添加成功！');
            } else {
                $this -> error('用户添加失败！');
            }
        }
    }

    protected function _update($name = "user") {
        $model = model('user');
        if (false === $model -> create()) {
            $this -> error($model -> getError());
        }
        $user_id = request('id');
        $model -> letter = get_letter($model -> name);
        $emp_no = $model -> emp_no;
        $name = $model -> name;
        $mobile_tel = $model -> mobile_tel;
        $is_del = $model -> is_del;
        $list = $model -> save();
        if (false !== $list) {
            if (get_system_config('system_license')) {
                if (!empty($mobile_tel)) {
                    import("Weixin.ORG.Util.Weixin");
                    $weixin = new \Weixin();
                    $mobile_tel = trim($mobile_tel, '+-');
                    $weixin -> add_user($emp_no, $name, $mobile_tel);
                    $weixin -> update_user($emp_no, $name, $mobile_tel, $is_del);
                }
            }
            $this -> assign('jumpUrl', get_return_url());
            $this -> success('编辑成功!');
        } else {
            //错误提示
            $this -> error('编辑失败!');
        }
    }

    //重置密码
    public function reset_pwd() {
        $user_id = post('user_id');
        $password = md5(request('password'));
        if ('' == trim($password)) {
            $this -> error('密码不能为空!');
        }

        $where[] = array('id', 'in', array_filter(explode(',', $user_id)));
        $result = model('user') -> where($where) -> set_field('password', $password);

        if ($result !== false) {
            $this -> assign('jump_url', get_return_url());
            $this -> success("密码修改成功");
        } else {
            $this -> error('重置密码失败！');
        }
    }

    function reset_salary_password() {
        $where[] = array('id', 'in', post('user_id'));
        $data['pay_pwd'] = '';
        $result = model('user') -> where($where) -> save($data);
        if (false !== $result) {
            $this -> assign('jump_url', get_return_url());
            $this -> success("重置工资密码成功");
        } else {
            $this -> error('清除密码失败！');
        }
    }

    public function password() {
        $this -> assign("id", request('id'));
        $this -> display();
    }

    function json() {
        header("Content-Type:text/html; charset=utf-8");
        $key = get('key');

        $model = new model('user');
        $where[] = array('name', 'like', $key);
        $where[] = array('emp_no', 'like', $key, 'or');
        $list = $model -> select('id,name') -> where($where) -> get_list();
        exit(json_encode($list));
    }

    function del() {
        $id = request('user_id');
        $admin_user_list = config('ADMIN_USER_LIST');

        if (!empty($admin_user_list)) {
            $where[] = array('notin', $admin_user_list);
        }
        $where[] = array('id', 'in', $id);

        $user_id = model('user') -> where($where) -> get_field('id', TRUE);
        $this -> _destory($user_id);
    }

    public function import() {
        $opmode = request('opmode');
        if ($opmode == "import") {
            $import_user = array();
            $File = model('File');
            $file_driver = config('DOWNLOAD_UPLOAD_DRIVER');
            $info = $File -> upload($_FILES, config('DOWNLOAD_UPLOAD'), config('DOWNLOAD_UPLOAD_DRIVER'), config("UPLOAD_{$file_driver}_CONFIG"));
            if (!$info) {
                $this -> error('上传错误');
            } else {
                //取得成功上传的文件信息
                //$uploadList = $upload -> getUploadFileInfo();
                Vendor('Excel.PHPExcel');
                //导入thinkphp第三方类库

                $import_file = $info['uploadfile']["path"];
                $import_file = substr($import_file, 1);

                $objPHPExcel = \PHPExcel_IOFactory::load($import_file);

                $dept = M("Dept") -> get_field('name,id');
                $position = M("Position") -> get_field('name,id');
                $role = M("Role") -> get_field('name,id');

                $sheetData = $objPHPExcel -> getActiveSheet() -> toArray(null, true, true, true);
                $model = model("User");
                for ($i = 2; $i <= count($sheetData); $i++) {
                    $data = array();
                    $data_user['emp_no'] = $sheetData[$i]["A"];
                    $data_user['name'] = $sheetData[$i]["B"];

                    $data_user['dept_id'] = $dept[$sheetData[$i]["C"]];
                    $data_user['position_id'] = $position[$sheetData[$i]["D"]];

                    $data_user['duty'] = $sheetData[$i]["J"];
                    $data_user['office_tel'] = $sheetData[$i]["F"];
                    $data_user['mobile_tel'] = $sheetData[$i]["G"];
                    $data_user['sex'] = $sheetData[$i]["H"];
                    $data_user['birthday'] = $sheetData[$i]["I"];
                    $data_user['openid'] = $sheetData[$i]["A"];
                    $data_user['westatus'] = 1;
                    $data_user['password'] = md5($sheetData[$i]["A"]);

                    if (empty($data_user['emp_no'])) {
                        $error[$i] = $sheetData[$i];
                        $error[$i]['desc'] = '员工编号不能为空';
                        continue;
                    }
                    if (empty($data_user['name'])) {
                        $error[$i] = $sheetData[$i];
                        $error[$i]['desc'] = '姓名不能为空';
                        continue;
                    }
                    if (empty($data_user['dept_id'])) {
                        $error[$i] = $sheetData[$i];
                        $error[$i]['desc'] = '部门不能为空';
                        continue;
                    }
                    if (empty($data_user['dept_id'])) {
                        $error[$i] = $sheetData[$i];
                        $error[$i]['desc'] = '部门不能为空';
                        continue;
                    }

                    if (empty($data_user['position_id'])) {
                        $error[$i] = $sheetData[$i];
                        $error[$i]['desc'] = '职位不能为空';
                        continue;
                    }

                    $where_check['emp_no'] = array('eq', $sheetData[$i]["A"]);
                    $check_count = model('User') -> where($where_check) -> count();

                    if (!empty($check_count)) {
                        $error[$i] = $sheetData[$i];
                        $error[$i]['desc'] = '用户已存在';
                        continue;
                    }

                    $user_id = M("User") -> add($data_user);
                    $import_user[] = $sheetData[$i]["A"];

                    $role_list = array_filter(explode(',', $sheetData[$i]["E"]));
                    $data_role = array();

                    foreach ($role_list as $key => $val) {
                        $data_role[] = $role[$val];
                    }
                    $this -> add_role($user_id, $data_role);
                }
                if (!empty($import_user)) {
                    $this -> _weixin_synconfig($import_user);
                    $this -> _sync_to_ldap($import_user);
                }

                $this -> assign('jumpUrl', get_return_url());
                if (empty($error)) {
                    $this -> success('导入成功！');
                    die ;
                } {
                    $this -> assign('error', $error);
                    $this -> display('error');
                    die ;
                }
            }
        } else {
            $this -> display();
        }
    }

    private function _weixin_synconfig($user_list) {
        if (get_system_config('system_license')) {
            import("Weixin.ORG.Util.Weixin");
            $weixin = new \Weixin($agent_id);

            $where['emp_no'] = array('in', $user_list);
            $where['is_del'] = array('eq', 0);
            $user_list = M("User") -> where(array('is_del' => 0)) -> get_field('emp_no,name,mobile_tel');

            $error_code_desc = config('WEIXIN_ERROR_CODE');

            foreach ($user_list as $key => $val) {
                $emp_no = $val['emp_no'];
                $name = $val['name'];
                $mobile_tel = trim($val['mobile_tel'], '+-');
                $error_code =                                                                        json_decode($weixin -> add_user($emp_no, $name, $mobile_tel)) -> errcode;

                $list[$key]['error_code'] = $error_code;
                $list[$key]['desc'] = $error_code_desc[$error_code];
                $list[$key]['emp_no'] = $key;
            }
            $this -> assign('weixin_list', $list);
        }
    }

    function add_role($user_id, $role_list) {
        $data['user_id'] = $user_id;

        foreach ($role_list as $role_id) {
            $data['role_id'] = $role_id;
            M('RoleUser') -> add($data);
        }
    }

    public function select_dept() {
        $dept_model = new model('dept');
        $where[] = array('is_del', 'eq', 0);
        $menu = $dept_model -> where($where) -> select('id,pid,name') -> order('sort asc') -> get_list();

        $tree = list_to_tree($menu);
        $this -> assign('tree', $tree);

        $root['id'] = 0;
        $root['name'] = '根节点';
        $root['child'] = $tree;

        $pid = array();
        $this -> assign('pid', $pid);
        $this -> display();
    }

    public function sync_to_wechat() {
        if (IS_AJAX) {
            $job_id = session('job_id');
            if (!empty($job_id)) {
                Vendor('WeChat.txl_api');
                $txl = new \TXL_API();
                sleep(1);
                echo $txl -> get_result($job_id);
                die ;
            } else {

                $tmp_file = tempnam(sys_get_temp_dir(), 'x');
                $fp = fopen($tmp_file, 'a');
                $title = array('姓名', '帐号', '手机号', '邮箱', '所在部门', '职位');
                fputcsv($fp, $title);

                $where['is_del'] = array('eq', 0);
                $user_list = D('UserView') -> where($where) -> getField('id,name,emp_no,mobile_tel,email,dept_id,position_name');

                foreach ($user_list as $val) {
                    unset($val['id']);
                    fputcsv($fp, $val);
                }

                fclose($fp);
                rename($tmp_file, $tmp_file . ".csv");
                echo $tmp_file . ".csv";

                Vendor('WeChat.media_api');
                Vendor('WeChat.txl_api');

                $agent_id = get_system_config("helper_agent_id");

                $api = new \MEDIA_API($agent_id);
                $txl = new \TXL_API();
                //test entry
                $info = array();
                $info["media"] = '@' . $tmp_file . ".csv";

                $ret = $api -> uploadMedia($info, "image");
                if (!empty($ret['errcode'])) {
                    echo $ret['errmsg'];
                    die ;
                }
                $media_id = $ret['media_id'];

                $data['media_id'] = $media_id;
                $txl_ret = $txl -> sync_user($data);

                $job_id = json_decode($txl_ret, true);
                $job_id = $job_id['jobid'];
                $job_id = session('job_id', $job_id);
                unlink($tmp_file . ".csv");
                die ;
            }
        }
        session('job_id', null);
        $this -> display();
        die ;
    }

}
